package auctionhausen

class BidService {

	def listingService

	def createBid(params) {
		def bidInstance = new Bid(params)
		def listingForBid = listingService.getListing(params?.listing?.id)
		if (listingForBid) {
			if (!listingService.isListingExpired(listingForBid)) {
				bidInstance.save(flush: true)
			} else {
				bidInstance.errors.reject(
						'bid.listing.expired',
						['listing', 'class Listing']as Object[],
						'Listing is expired')
			}
		}
		else {
			bidInstance.errors.reject(
					'bid.listing.does.not.exist',
					['listing', 'class Listing']as Object[],
					'Listing no longer exists')
		}

		return bidInstance
	}

	def getMinimumBidAmountForListing(Listing listing) {
		def queryParams = [
			sort : "amount",
			order : "desc",
			max : 1]
		def bids = Bid.findByListingID(listing.id)
		if (!bids.isEmpty()) {
			return bids[0].amount
		}
	}
}
